package com.example.forum.controller;


import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.config.AppConfig;
import com.example.forum.model.Message;
import com.example.forum.model.User;
import com.example.forum.services.IMessageService;
import com.example.forum.services.IUserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

//站内信
@RestController
@Slf4j
@RequestMapping("/message")
public class MessageController {
    @Resource
    private IMessageService messageService;
    @Resource
    private
    IUserService userService;
    //发送站内信
    @PostMapping("/send")
    public AppResult send (HttpServletRequest request, @RequestParam(value = "receiveUserId") @NonNull Long receiveUserId,
                            @RequestParam(value = "content") @NonNull String content) {
        // 获取发送用户信息
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 判断是否被禁⾔
        if (user.getState() != 0) {
            // ⽇志
            log.warn(ResultCode.FAILED_USER_BANNED.toString() + ", userId = "
                    + user.getId());
            // 返回错误信息
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 不能给⾃⼰发送
        if (user.getId() == receiveUserId) {
            // ⽇志
            log.warn("不能给⾃⼰发送站内信. postUserId = " + user.getId() + ", receiveUserId = " + receiveUserId);
            // 返回错误信息
            return AppResult.failed(ResultCode.FAILED_CREATE);
        }
        // 查询接收
        User receiveUser = userService.selectById(receiveUserId);
        // ⽬标不存在
        if (receiveUser == null || receiveUser.getDeleteState() != 0) {
            // ⽇志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString() + ", receiveUserId = " + receiveUserId);
             // 返回错误信息
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        // 构造对象
        Message message = new Message();
        message.setPostUserId(user.getId());
        message.setReceiveUserId(receiveUserId);
        message.setContent(content);
        // 调⽤业务层
        messageService.create(message);
        // 返回结果
        return AppResult.success();
    }

    //获取未读消息个数
    @GetMapping("/getUnreadCount")
    public AppResult<Integer> getUnreadCount (HttpServletRequest request) {
        // 获取发送信息
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 查询未读消息个数
        Integer result = messageService.selectUnreadCount(user.getId());
        // 返回结果
        return AppResult.success(result);
    }

    //查询所有站内信
    @GetMapping("/getAll")
    public AppResult<List<Message>> getAll(HttpServletRequest request) {
        // 获取当前登录⽤⼾
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 获取⽤⼾站内信
        List<Message> result = messageService.selectByReceiveUserId(user.getId());
        // 返回结果
        return AppResult.success(result);
    }

    //更新状态为已读
    @PostMapping("/markRead")
    public AppResult markRead (HttpServletRequest request,
                               @RequestParam(value = "id") @NonNull Long id) {
        // 根据Id查询内容
        Message message = messageService.selectById(id);
        // 获取⽤⼾信息
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 接收⽅不是⾃⼰
        if (message != null && user.getId() != message.getReceiveUserId()) {
            // 打印⽇志
            log.warn("查询了不属于⾃⼰的站内信：userId = " + user.getId() + ", receiveUserId = " + message.getReceiveUserId());
                    // 返回错误结果
            return AppResult.failed(ResultCode.FAILED);
        }
        // 更新为已读状态
        messageService.updateStateById(message.getId(), (byte) 1);
        // 返回结果
        return AppResult.success();
    }

    //回复站内信
    @PostMapping("/reply")
    public AppResult reply (HttpServletRequest request,
                            @RequestParam("repliedId")
                            @NonNull Long repliedId,
                            @RequestParam("content")
                            @NonNull String content) {
        // 校验当前登录用户的状态
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1) {
            // 返回错误描述
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 校验要回复的站内信状态
        Message existsMessage = messageService.selectById(repliedId);
        if (existsMessage == null || existsMessage.getDeleteState() == 1) {
            // 返回错误描述
            return AppResult.failed(ResultCode.FAILED);
        }
        // 不能给⾃⼰回复
        if (user.getId() == existsMessage.getPostUserId()) {
            // 返回错误描述
            return AppResult.failed("不能回复自己的站内信");
        }
        // 构造对象
        Message message = new Message();
        message.setPostUserId(user.getId()); // 发送者
        message.setReceiveUserId(existsMessage.getPostUserId()); // 接收者
        message.setContent(content); // 内容
        // 调⽤Service
        messageService.reply(repliedId, message);
        // 返回结果
        return AppResult.success();
    }

}
